package com.my.thread;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.entity.AttendanceLog;
import com.my.entity.NightSpot;
import com.my.entity.Setting;
import com.my.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

@Component
public class ClockInThread extends Thread {

    SimpleDateFormat format = new SimpleDateFormat("HH:mm:00");
    SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private CurriculumService cService;
    @Autowired
    private AttendanceLogService aalService;
    @Autowired
    private NightSpotService nsService;
    @Autowired
    private SettingService sService;
    private LinkedList<Map<String, Object>> maps = new LinkedList<>();
    private String currentDate, oldDate;


    @Override
    public void run() {
        while (true) {
            Date date = new Date();
            currentDate = format.format(new Date());
            oldDate = currentDate;
            maps.addAll(cService.getUserCurriculum(format.format(date)));
            Setting setting = sService.getOne(new QueryWrapper<Setting>().eq("setting_key", "nightSpotStartTime"));
            String nsDate = format.format(DateUtil.offsetMinute(DateUtil.parse(setting.getSettingValue(), format), 1));
            if(nsDate.equals(currentDate)) {
                for (Map<String, Long> map : nsService.getNotSpotUserId()) {
                    boolean flag = map.get("status") != null;
                    nsService.save(new NightSpot().setUserId(map.get("id")).setConfirm(true).setStatus(flag ? 2 : 4).setRemarks(flag ? "申请晚归" : "未签到"));
                }
            }
            for (Iterator ite = maps.iterator(); ite.hasNext();) {
                Map<String, Object> map = (Map<String, Object>) ite.next();
                if (Convert.toStr(map.get("endTime")).equals(currentDate)) {
                    AttendanceLog log = aalService.getByUserAttendCreate(Convert.toLong(map.get("userId")), Convert.toLong(map.get("curriculumId")), formatDate.format(date));
                    if (log == null) {
                        aalService.save(new AttendanceLog().setUserId(Convert.toLong(map.get("userId"))).setCurriculumId(Convert.toLong(map.get("curriculumId"))).setStatus(Convert.toInt(map.get("status"), 0) == 0 ? 2 : 4));
                        ite.remove();
                    }
                }
            }
            while (oldDate.equals(currentDate)) {
                currentDate = format.format(new Date());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}